package com.eapi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eapi.eapicommom.model.entity.InterfaceInfo;
import com.eapi.eapicommom.model.entity.User;
import com.eapi.project.annotation.AuthCheck;
import com.eapi.project.common.BaseResponse;
import com.eapi.project.common.DeleteRequest;
import com.eapi.project.common.ErrorCode;
import com.eapi.project.common.ResultUtils;
import com.eapi.project.constant.CommonConstant;
import com.eapi.project.constant.UserConstant;
import com.eapi.project.exception.BusinessException;
import com.eapi.project.model.dto.article.ArticleCommentAddRequest;
import com.eapi.project.model.dto.article.ArticleCommentQueryRequest;
import com.eapi.project.model.dto.comment.CommentQueryRequest;
import com.eapi.project.model.dto.comment.CommentUpdateRequest;
import com.eapi.project.model.entity.Article;
import com.eapi.project.model.entity.Articlecomment;
import com.eapi.project.model.entity.Comment;
import com.eapi.project.model.vo.CommentVO;

import com.eapi.project.model.vo.PageVo;
import com.eapi.project.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/articleComment")
public class ArticleCommentController {

    @Resource
    private ArticlecommentService articlecommentService;


    @Resource
    private UserService userService;

    @Resource
    private ArticleService articleService;

    // region 增删改查

    /**
     * 创建
     *
     * @param commentAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<String> addComment(@RequestBody ArticleCommentAddRequest commentAddRequest, HttpServletRequest request) {
        Article article = articleService.getById(commentAddRequest.getArticleId());
        if(article.getIsComment().equals("0")){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"该文章不允许评论");
        }
        if (commentAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(StringUtils.isBlank(commentAddRequest.getContext())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"评论内容不能为空");
        }

        Articlecomment articlecomment = new Articlecomment();
        BeanUtils.copyProperties(commentAddRequest, articlecomment);
        // 获取当前登录用户的id和姓名
        User loginUser = userService.getLoginUser(request);
        String userName = loginUser.getUserName();
        if(userName == null){
            articlecomment.setUsername(loginUser.getUserAccount());
        }
        else{
            articlecomment.setUsername(loginUser.getUserName());
        }
        articlecomment.setUserId(loginUser.getId());
        articlecommentService.save(articlecomment);

        // interface表中的评论数加一
        /*interfaceInfo.setComments(interfaceInfo.getComments()+1);
        interfaceInfoService.updateById(interfaceInfo);
        long newCommentId = comment.getId();*/
        return ResultUtils.success("评论成功");
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteComment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Articlecomment oldComment = articlecommentService.getById(id);
        if (oldComment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //校验权限
        boolean permissionCheck = !oldComment.getUserId().equals(user.getId()) && !user.getUserRole().equals(UserConstant.ADMIN_ROLE);

        // 仅本人或管理员可删除
        if (permissionCheck) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = articlecommentService.removeById(id);
        // interface表中的评论数减一
        return ResultUtils.success(b);
    }

    /**
     * 分页获取列表
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<PageVo> listCommentByPage(ArticleCommentQueryRequest articleCommentQueryRequest, HttpServletRequest request) {
        long current = articleCommentQueryRequest.getCurrent();
        long size = articleCommentQueryRequest.getPageSize();
        QueryWrapper<Articlecomment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("articleId", articleCommentQueryRequest.getArticleId());
        queryWrapper.orderByDesc("createTime");
        Page page = new Page<>(current, size);
        Page commentPage = articlecommentService.page(page, queryWrapper);
        List<Articlecomment> commentPageRecords = commentPage.getRecords();
        for (Articlecomment commentPageRecord : commentPageRecords) {
            commentPageRecord.setAvatar(userService.getById(commentPageRecord.getUserId()).getUserAvatar());
        }
        PageVo commentPageVo = new PageVo(commentPageRecords, commentPage.getTotal());
        return ResultUtils.success(commentPageVo);
    }
}
